'''
Created on Apr 08, 2011

@author: Elia Contini
'''

from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.db.models.aggregates import Count
from django.db.utils import IntegrityError
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from django.utils.translation import ugettext as _

# remember repository. for deployment
from core.models import Collection, Content, Course
from core import MEutils

@login_required
def collection_new(request, courseId):
	user = MEutils.getUser(request.session)
	role = MEutils.getUserRole(user)
	course = Course.objects.filter(id = courseId)[0] # TODO - what happens if course doesn't exist?
	data = dict() # will contain validated data ready to store
	feedback = list()
	
	if request.method == 'POST':
		name = request.POST.get('name').strip()
		description = request.POST.get('description').strip()
		shareWith = request.POST.getlist('shareWith')
		#tags = request.POST.get('tags').strip()
		collection = None
		
		# name
		if len(name) < 3:
			feedback.append('<p class="error">' + _("[MESSAGE] Name must be at least 3 characters long.") + '</p>')
		else:
			data['name'] = name
		
		# description	
		if len(description) < 8:
			feedback.append('<p class="error">' + _("[MESSAGE] Description must be at least 8 characters long.") + '</p>')
		else:
			data['description'] = description
			
		# shareWith
		if len(shareWith) == 0:
			feedback.append('<p class="error">' + _("[MESSAGE] Choose students involved.") + '</p>')
		else:
			data['students'] = shareWith
		
		# try to create collection
		if len(feedback) == 0:
			collection = Collection(teacher = user, name = name, description = description, course = course)
			
			try:
				collection.save()
				for s in data['students']:
					collection.students.add(User.objects.filter(id = s)[0])
				
				feedback.append('<p class="success">' + _("[MESSAGE] The folder has been created.") + '</p>')
				request.session['feedback'] = feedback
				return HttpResponseRedirect("/mrEdu/" + role + "/collections")
			except IntegrityError:
				feedback.append('<p class="error">' + _("[MESSAGE] The folder") + ' <strong>' +name + '</strong> ' +_("[MESSAGE] already exists.") + '</p>')

	return render_to_response('teacher_collection_new.html', {'section': 'course', 'user': user, 'userRole': role, 'course': course, 'formData': data, 'feedback': feedback, }, context_instance=RequestContext(request))

@login_required
def course(request, courseId):
	user = MEutils.getUser(request.session)
	course = Course.objects.filter(id = courseId)[0] # TODO - what happens if course doesn't exist?
	collections = Collection.objects.filter(course__id = courseId)
	students = list()
	
	for s in course.students.all():
		student = dict()
		student['name'] = s.first_name
		student['surname'] = s.last_name
		student['contents'] = Content.objects.filter(user = s, collection__in = collections).count()
		students.append(student)
		
	return render_to_response('teacher_course.html', {'section': 'course', 'user': user, 'userRole': MEutils.getUserRole(user), 'course': course, 'students': students, 'collections': collections, }, context_instance=RequestContext(request))

@login_required
def course_choose(request):
	user = MEutils.getUser(request.session)
	role = MEutils.getUserRole(user)
	courses = Course.objects.filter(teacher = user)
	feedback = list()
	
	if request.method == 'POST':
		course = request.POST.get('class').strip()
		
		if course != 'none':
			return HttpResponseRedirect("/mrEdu/" + role + "/class/" + course + "/collection/new")
		else:
			feedback.append('<p class="error">' + _("[MESSAGE] Choose a class.") + '</p>')
	
	return render_to_response('teacher_course_choose.html', {'section': 'collection', 'user': user, 'userRole': role, 'courses': courses, 'feedback': feedback, }, context_instance=RequestContext(request))

@login_required
def courses(request):
	user = MEutils.getUser(request.session)
	data = list()
	courses = Course.objects.filter(teacher__id = user.id).order_by('name').annotate(studentsNum = Count('students'))
	collections = None
	contents = None
	
	for course in courses:
		collections = Collection.objects.filter(teacher__id = user.id, course__id = course.id)
		contents = Content.objects.filter(collection__in = collections)
		data.append(
				{
				'id': course.id,
				'name': course.name,
				'year': course.year,
				'studentsNum': course.studentsNum,
				'collectionsNum': len(collections),
				'contentsNum': len(contents),
				})
	
	return render_to_response('teacher_courses.html', {'section': 'course', 'user': user, 'userRole': MEutils.getUserRole(user), 'courses': data, }, context_instance=RequestContext(request))

@login_required
def index(request):
	user = MEutils.getUser(request.session)
	content = Content.objects.filter(collection__teacher = user).order_by('creation_date')[:10]
	return render_to_response('teacher_index.html', {'section': 'dashboard', 'user': user, 'userRole': MEutils.getUserRole(user), 'content': content, }, context_instance=RequestContext(request))
